const express = require("express");
const router = express.Router();
const {
  getAvailableCoupons,
  validateCoupon,
  calculateDiscount,
  applyCoupons,
  useCoupon,
} = require("../utils/sql");

// 获取可用优惠券列表
router.post("/getAvailableCoupons", async (req, res) => {
  try {
    const { user_id } = req.body;
    
    const coupons = await getAvailableCoupons(user_id);
    
    return res.status(200).json({
      code: 200,
      message: "获取成功",
      data: coupons
    });
  } catch (err) {
    console.error("获取优惠券列表失败:", err);
    return res.status(500).json({
      code: 0,
      message: "服务器错误"
    });
  }
});

// 验证优惠券
router.post("/validateCoupon", async (req, res) => {
  try {
    const { code, amount, user_id } = req.body;
    
    if (!code || !amount) {
      return res.status(400).json({
        code: 0,
        message: "参数不完整"
      });
    }

    const coupons = await validateCoupon(code, amount, user_id);
    
    if (coupons.length === 0) {
      return res.status(400).json({
        code: 0,
        message: "优惠券无效或不满足使用条件"
      });
    }

    const coupon = coupons[0];
    const discount = calculateDiscount(coupon, amount);
    
    return res.status(200).json({
      code: 200,
      message: "优惠券验证成功",
      data: {
        coupon: coupon,
        discount: discount,
        finalAmount: Math.max(0, amount - discount)
      }
    });
  } catch (err) {
    console.error("验证优惠券失败:", err);
    return res.status(500).json({
      code: 0,
      message: "服务器错误"
    });
  }
});

// 计算多张优惠券的折扣
router.post("/calculateCouponsDiscount", async (req, res) => {
  try {
    const { coupon_codes, amount } = req.body;
    
    if (!coupon_codes || !Array.isArray(coupon_codes) || !amount) {
      return res.status(400).json({
        code: 0,
        message: "参数不完整"
      });
    }

    // 验证所有优惠券
    const validCoupons = [];
    for (const code of coupon_codes) {
      const coupons = await validateCoupon(code, amount);
      if (coupons.length > 0) {
        validCoupons.push(coupons[0]);
      }
    }

    if (validCoupons.length === 0) {
      return res.status(400).json({
        code: 0,
        message: "没有可用的优惠券"
      });
    }

    // 计算叠加折扣
    const result = applyCoupons(validCoupons, amount);
    
    return res.status(200).json({
      code: 200,
      message: "计算成功",
      data: result
    });
  } catch (err) {
    console.error("计算优惠券折扣失败:", err);
    return res.status(500).json({
      code: 0,
      message: "服务器错误"
    });
  }
});

module.exports = router;
